package com.cn.service.impl;

import java.util.UUID;

import com.cn.dao.UserDao;
import com.cn.dao.impl.UserDaoImpl2;
import com.cn.domain.User;
import com.cn.service.UserService;
import com.cn.utils.JdbcUtils;
import com.cn.utils.MD5Utils;

public class UserServiceImpl implements UserService {
	
	private UserDao ud = new UserDaoImpl2();
	
	public void register(User u) {
		
		JdbcUtils.getConnectionWithTransaction();
		try {
			User user = ud.getUserByUserName(u);
			if (user != null) {
				throw new RuntimeException("用户名已存在！");
			}
			u.setPassword(MD5Utils.md5(u.getPassword()));
//---------------------生成激活码---------------------------
			//1、生成激活码
			String activecode = UUID.randomUUID().toString();
			//2、给用户发邮件
			//MailUtils.sendMail(u.getEmail(), "<a href='http://192.168.1.121:8080/day1302/ActiveCodeServlet?activecode="+activecode+"'>click me and you will finish active!</a>");
			u.setActivecode(activecode);
//---------------------生成激活码---------------------------
			ud.save(u);
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
		JdbcUtils.commit();
	}
	public User login(User u) {
		JdbcUtils.getConnectionWithTransaction();
		User user;
		try {
			user = ud.getUserByUserName(u);
			if(user==null){
				throw new RuntimeException("用户名不存在！");
			}
			//System.out.println("数据库中的："+user.getPassword());//加了一次密
			//System.out.println(u.getPassword());//加了两次密的
			if(!user.getPassword().equals(u.getPassword())){
				throw new RuntimeException("密码不正确");
			}
			if(user.getIsactive()==0){
				throw new RuntimeException("请先激活，再登录！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
		JdbcUtils.commit();
		return user;
	}
	public User getUserByUserName(String name) {
		JdbcUtils.getConnectionWithTransaction();
		User u = ud.getUserByUserName(name);
		JdbcUtils.commit();
		return u;
	}
	public void toActiveCode(String activecode) {
		JdbcUtils.getConnectionWithTransaction();
		User user = ud.getUserByActiveCode(activecode);
		if(user==null){
			throw new RuntimeException("激活码不正确");
		}
		if(user.getIsactive()==1){
			throw new RuntimeException("请不要重复激活");
		}
		ud.updateActive(user.getId(), 1);
		JdbcUtils.commit();
	}
	public void updateUser(User user) {
		JdbcUtils.getConnectionWithTransaction();
		try {
			//User u = ud.getUserByUserId(user.getId());
			user.setPassword(MD5Utils.md5(user.getPassword()));
			ud.updateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			JdbcUtils.rollback();
			throw new RuntimeException(e.getMessage());
		}
		JdbcUtils.commit();
		
	}
	
}
